import path from 'path'
import { spawnSync } from 'child_process'
import npmWhich from 'npm-which'
import _debug from 'debug'

import { fileExists } from '../utils'

const debug = _debug('build-tools:lint')
const which = npmWhich(__dirname)
const args = process.argv.slice(2)

// if `.eslintrc` found then use it instead built-in `eslintrc.js`
const config = !fileExists('.eslintrc')
  ? ['--config', path.join(__dirname, '../config/eslintrc.js')]
  : []

// if `.eslintignore` found then use it instead built-in `eslintignore`
const ignore = !fileExists('.eslintignore')
  ? ['--ignore-path', path.join(__dirname, '../config/.eslintignore')]
  : []

debug(`Run eslint from ${which.sync('eslint')}`)
debug(`With config: ${config.join(' ')}`)
debug(`With ignore: ${ignore.join(' ')}`)
debug(`With other args: ${args}`)

const result = spawnSync(
  which.sync('eslint'),
  [...config, ...ignore, ...args],
  {
    stdio: 'inherit',
    env: process.env,
  },
)

process.exit(result.status)
